<template>
  <div class="login-wrapper">
    <section class='login-body'>
      <div class="illustration">
        <img src="~assets/img/illustration@2x.png" alt="">
      </div>
      <div class="info">
        <div class="login-type"
          v-show="loginType === 'account'">
          <!-- <div class="login-type-icon account"
            @click="cutoverLoginType('scanCode')"></div>
          <div class="tip">扫码登录更安全</div> -->
          <div class="logo-name">
            <p class="logo"></p>
            <p class="name">数字化营销平台-运维</p>
          </div>
          <ul class="form-list">
            <li
              @click="handleInputFocus('mobile')"
              class="form-item">
              <p class="icon mobile"></p>
              <p class="text">
                <input
                  @focus="focused('mobile')"
                  @blur="loseFocus()"
                  :class="{active: currType === 'mobile', warn: warn === 1}"
                  v-model.trim="loginForm.number"
                  ref="mobile"
                  placeholder="请输入账号进行登录"
                  type="text">
              </p>
            </li>
            <li
              @click="handleInputFocus('pwd')"
              class="form-item">
              <p class="icon password"></p>
              <p class="text">
                <input
                  @focus="focused('pwd')"
                  @blur="loseFocus()"
                  :class="{active: currType === 'pwd', warn: warn === 2}"
                  v-model.trim="loginForm.password"
                  ref="pwd"
                  placeholder="请输入密码"
                  type="password">
              </p>
            </li>
            <li
              class="form-item">
              <p class="icon captcha" @click="handleInputFocus('captcha')"></p>
              <p class="text" @click="handleInputFocus('captcha')">
                <input
                  @focus="focused('captcha')"
                  @blur="loseFocus()"
                  :class="{active: currType === 'captcha', warn: warn === 3}"
                  v-model.trim="loginForm.captcha"
                  ref="captcha"
                  placeholder="请输入验证码"
                  type="text">
              </p>
              <div class="captcha-wrapper" @click="updateCaptcha"
                v-loading="loadingCaptcha" element-loading-spinner="el-icon-loading">
                <img class="captcha-img" v-show="captchaUrl" :src="captchaUrl"/>
              </div>
            </li>
            <div class="remember-forget">
              <p class="remember">
                <el-checkbox v-model="checked">记住密码</el-checkbox>
              </p>
              <!-- <p @click="handleForget()" class="forget">忘记密码</p> -->
            </div>
            <div @click="handleLogin()" class="btn"><i v-show="isLoading" class="el-icon-loading"></i>登录</div>
            <!-- <div @click="handleRegistered()" class="registere">立即注册</div> -->
          </ul>
        </div>
        <div class="login-type"
          v-show="loginType === 'scanCode'">
          <div class="login-type-icon sacncode"
            @click="cutoverLoginType('account')"></div>
          <div class="tip">密码登录</div>
          <div class="logo-name">
            <p class="logo"></p>
            <p class="name">数字化营销平台</p>
          </div>
          <div class="scan-code"
            v-show="scanCodeStatus === 1">
            <p class="qrcode">
              <img :src="qrCodeUrl" alt="">
            </p>
            <p class="descript icon-scancode">请您使用在账户信息中绑定的微信扫码完成登录</p>
          </div>
          <div class="scan-code"
            v-show="scanCodeStatus === 2">
            <div class="qrcode invalid">
              <img src="https://test.saas.yuemia.com/mmbiz_jpg/wSAQiaXEKSBsYiadrdqIIJUUOJDvlSV5bFUvNLU4dmU3aeRLia3h4kE6EvZHxuCTYGEkhNxDjmkJZTlLohAIeslow/0" alt="">
              <p class="succ">扫码成功</p>
            </div>
            <p class="descript">正在进入系统，请稍等…</p>
          </div>
          <div class="scan-code"
            v-show="scanCodeStatus === 3">
            <div class="qrcode invalid">
              <img src="https://test.saas.yuemia.com/mmbiz_jpg/wSAQiaXEKSBsYiadrdqIIJUUOJDvlSV5bFUvNLU4dmU3aeRLia3h4kE6EvZHxuCTYGEkhNxDjmkJZTlLohAIeslow/0" alt="">
              <p class="fail">扫码失败</p>
            </div>
            <p class="descript">当前微信未绑定平台账号</p>
            <p class="descript">
              请尝试<span class='descript-btn' @click='resetScanCode'>重新扫码</span>
            </p>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import JSEncrypt from 'jsencrypt'
import { getPubKey } from '@/api/login.js'
export default {
  data () {
    return {
      // 登录方式：account代表账号登陆，scanCode代表扫码登录
      loginType: 'account',
      // 账号登录相关
      loginForm: {
        number: '',
        password: '',
        captcha: ''
      },
      rules: {
        number: [{ required: true, trigger: 'blur' }],
        password: [{ required: true, trigger: 'blur' }]
      },
      isLoading: false,
      // userId: '',
      checked: false, // 是否记住密码
      currType: '', // 控制输入框高亮
      warn: 0, // 账号密码不能为空1代表账号为空，2代表密码为空
      captchaUrl: '',
      uuid: '',
      loadingCaptcha: false,
      // 扫码登录相关
      qrCodeUrl: 'https://test.saas.yuemia.com/mmbiz_jpg/wSAQiaXEKSBsYiadrdqIIJUUOJDvlSV5bFUvNLU4dmU3aeRLia3h4kE6EvZHxuCTYGEkhNxDjmkJZTlLohAIeslow/0',
      scanCodeStatus: 1 // 扫码状态:1代表未扫码,2代表扫码成功,3代表扫码失败
    }
  },
  methods: {
    // 重新扫码
    resetScanCode () {
      this.scanCodeStatus = 1
    },
    // 切换登录方式
    cutoverLoginType (type) {
      this.loginType = type
    },
    // 注册点击事件
    handleRegistered () {
      this.linkTo({name: 'Registered'})
    },
    // 忘记密码点击事件
    handleForget () {
      this.linkTo({name: 'Reset'})
    },
    // 登录
    async handleLogin () {
      if (!this.loginForm.number) {
        return this.$message({
          message: '请输入账号',
          type: 'warning'
        })
      // } else if (!this.checkTel(this.loginForm.number)) {
      //   return this.$message({
      //     message: '请输入正确的手机号',
      //     type: 'warning'
      //   })
      } else if (!this.loginForm.password) {
        return this.$message({
          message: '请输入密码',
          type: 'warning'
        })
      } else if (!this.loginForm.captcha) {
        return this.$message({
          message: '请输入验证码',
          type: 'warning'
        })
      }
      this.isLoading = true
      // rsa加密
      const encrypt = new JSEncrypt()
      let pubKey = await this.getRsaPublicKey()
      encrypt.setPublicKey(pubKey)
      console.log('this.loginForm.password： ', this.loginForm.password)
      let password = encrypt.encrypt(this.loginForm.password)
      console.log('=== password ===: ', password)
      let url = `/login`
      let params = {
        account: this.loginForm.number,
        password: password,
        uuid: this.uuid,
        code: this.loginForm.captcha
      }
      this.post(url, params).then(res => {
        this.isLoading = false
        if (res.data.code === 200) {
          this.rememberLoginInfo()
          // this.userId = res.data.data.openid
          // this.currentUserIdFn(res.data.data.openid)
          // sessionStorage.setItem('userId', res.data.data.openid)
          // sessionStorage.setItem('accountId', res.data.data.accountId)
          sessionStorage.setItem('accessToken', res.data.data.token)
          sessionStorage.setItem('refreshToken', res.data.data.refreshToken)
          sessionStorage.setItem('timestamp', new Date().getTime())
          setTimeout(() => {
            sessionStorage.setItem('hasLogin', true)
            this.linkTo({name: 'platformList'})
          }, 1000)
        } else {
          this.updateCaptcha()
        }
      }).catch(e => {
        this.isLoading = false
        this.handleError(e)
      })
    },
    // 登录时设置记住密码
    rememberLoginInfo () {
      // 本地存储用户账号
      if (this.checked) {
        localStorage.setItem('loginInfo', JSON.stringify(this.loginForm))
      } else {
        localStorage.removeItem('loginInfo')
      }
    },
    // 点击聚焦
    handleInputFocus (type) {
      this.$refs[type].focus()
    },
    // 聚焦时输入框高亮
    focused (type) {
      this.currType = type
      this.warn = 0
    },
    // 失焦时输入框取消高亮
    loseFocus () {
      this.currType = ''
      if (!this.loginForm.number) {
        this.warn = 1
      // } else if (!this.checkTel(this.loginForm.number)) {
      //   this.warn = 1
      } else if (!this.loginForm.password) {
        this.warn = 2
      } else {
        this.warn = 0
      }
    },
    // 获取登录公钥
    getRsaPublicKey () {
      return new Promise(resolve => {
        getPubKey().then(res => {
          if (res.data.code === 200 && res.data.data) {
            resolve(res.data.data)
          }
        })
      })
    },
    // 获取验证码图片
    updateCaptcha () {
      this.loadingCaptcha = true
      this.uuid = this.createUniqueId()
      let url = '/getCaptcha'
      let params = {
        uuid: this.uuid
      }
      this.get(url, params).then(res => {
        if (res.data.code === 200) {
          setTimeout(() => {
            this.loadingCaptcha = false
            this.captchaUrl = res.data.data || ''
          }, 300)
        }
      })
    }
  },
  created () {
    this.updateCaptcha()
    let loginInfo = JSON.parse(localStorage.getItem('loginInfo'))
    if (loginInfo) {
      this.loginForm = loginInfo
      this.loginForm.captcha = ''
      this.checked = true
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      // 如果用户已经登录，直接跳首页
      if (sessionStorage.getItem('hasLogin')) {
        vm.linkTo({name: 'platformList'})
      }
    })
  }
}
</script>

<style lang="stylus" scoped>
::-webkit-input-placeholder /* WebKit browsers */
  font-size: 14px;
  color: #93939D;
:-moz-placeholder /* Mozilla Firefox 4 to 18 */
  font-size: 14px;
  color: #93939D;
::-moz-placeholder /* Mozilla Firefox 19+ */
  font-size: 14px;
  color: #93939D;
:-ms-input-placeholder /* Internet Explorer 10+ */
  font-size: 14px;
  color: #93939D;
// 使用记住密码并自动填充后，输入框会出现黄色/灰色的浏览器默认样式
input:-webkit-autofill
  -webkit-box-shadow: 0 0 0px 1000px #ffffff inset!important;
  -webkit-text-fill-color: #3E3E3E !important;
.login-wrapper
  width 100%
  height 100%
  overflow-x auto
  overflow-y auto
  center()
  background url('~assets/img/login_bg@2x.png') no-repeat center / cover
  .login-body
    width 1000px
    height 494px
    display flex
    .illustration
      width 593px
      height 100%
      background: #4C84FF url('~assets/img/login_bg2@2x.png') no-repeat center / 100%;
      box-shadow: 0px 8px 16px 0px rgba(16, 41, 94, 0.29);
      border-radius: 13px 0px 0px 13px;
      padded_box(border-box, 108px 0 0 99px)
      img
        display block
        width 318px
    .info
      width 406px
      height: 100%;
      .login-type
        width 100%
        height: 100%;
        background: #FFFFFF;
        box-shadow: 0px 8px 16px 0px rgba(15, 45, 106, 0.12);
        border-radius: 0px 13px 13px 0px;
        padded_box(border-box, 55px 45px 0)
        position relative
        .login-type-icon
          width 76px
          height 76px
          background  no-repeat center/100%
          position absolute
          top 0px
          right 0px
          &.account
            background-image url('~assets/img/icon_account@2x.png')
          &.sacncode
            background-image url('~assets/img/icon_sacncode@2x.png')
        .tip
          height: 26px;
          text-align center
          line-height 24px
          background: rgba(255, 178, 0, 0.1);
          border: 1px solid #FFB200;
          padded_box(border-box, 0 8px)
          border-radius 4px
          font-size 12px
          color #FFB200
          position absolute
          top 24px
          right 72px
          &::before
            content ''
            display block
            width: 0;
            height: 0;
            border-style: solid;
            border: 6px solid transparent;
            border-left: 6px solid #FFB200;
            position: absolute;
            right: -12px;
            top: 50%;
            transform translate(0, -50%)
          &::after
            content ''
            display block
            width: 0;
            height: 0;
            border-style: solid;
            border: 4px solid transparent;
            border-left: 4px solid rgb(255,247,229);
            position: absolute;
            right: -8px;
            top: 50%;
            transform translate(0, -50%)
        .logo-name
          width 100%
          .logo
            width 36px
            height 36px
            background url('~assets/img/artical1.png') no-repeat center / cover
            margin 0 auto
          .name
            margin-top 10px
            line-height 19px
            font-size 18px
            color: #3A3A3A;
            text-align center
        // 账号登录
        .form-list
          width 100%
          // margin-top 20px
          margin-top 40px
          .form-item
            width 100%
            position relative
            display flex
            & + .form-item
              margin-top 20px
            .text
              flex 1
              input
                display block
                width 100%
                height 40px
                line-height 20px
                padded_box(border-box,10px 7px 10px 32px)
                border-radius 6px
                border: 1px solid #E9EAED;
                font-size: 16px;
                outline none
                &.active
                  border-color #4C84FF
                &.warn
                  border-color #F56C6C
            .icon
              width 20px
              height 20px
              background-repeat no-repeat
              background-position center
              background-size 100%
              margin-right 8.4px
              position absolute
              top 50%
              left 7px
              transform translate(0, -50%)
              &.mobile
                background-image url('~assets/img/login_mobile@2x.png')
              &.password
                background-image url('~assets/img/login_password@2x.png')
              &.captcha
                width 17px
                height 17px
                left 9px
                background-image url('~assets/img/login_captcha.png')
            .captcha-wrapper
              flex none
              width 150px
              height 40px
              border-radius 6px
              border: 1px solid #E9EAED;
              margin-left 10px
              box-sizing border-box
              cursor pointer
              .captcha-img
                display block
                width 100%
                height 100%
              >>> .el-loading-spinner
                height 100%
                display flex
                align-items center
                justify-content center
                padding-top 2px
                .el-icon-loading
                  width 20px
                  height 20px
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  &::before
                    font-size 18px
                    color #949494
          .remember-forget
            display flex
            justify-content space-between
            align-items center
            margin-top 17px
            >>> .el-checkbox
              color #7f7f7f
              &.is-checked
                .el-checkbox__label
                  color #7f7f7f
                  font-size 12px
              .el-checkbox__inner
                width 14px
                height 14px
                &::after
                  width 2px
                  height 6px
            .remember,.forget
              color #7f7f7f
              font-size 12px
              cursor pointer
          .btn
            width 100%
            height 40px
            line-height 40px
            text-align center
            background: #4C84FF;
            border-radius 6px
            font-size 14px
            color #fff
            margin-top 40px
            cursor pointer
            .el-icon-loading
              margin-right 4px
          .registere
            font-size 12px
            color: #4C84FF;
            line-height 14px
            margin-top 17px
      // 扫码登录
      .scan-code
        display flex
        flex-direction column
        align-items center
        .qrcode
          width 150px
          height 150px
          margin 40px auto
          // border 1px solid #ddd
          // border-radius 4px
          position relative
          &.invalid
            img
              opacity 0.2
          img
            display block
            width 100%
          .succ
            width 106px
            height: 40px;
            line-height 16px
            background: #FFFFFF url('~assets/img/icon_succ@2x.png') no-repeat 10px center / 16px;
            box-shadow: 0px 0px 6px 2px rgba(0, 0, 0, 0.06);
            border-radius: 8px;
            padded_box(border-box, 12px 10px 12px 38px)
            font-size 14px
            color #222222
            position absolute
            top 50%
            left 50%
            transform translate(-50%, -50%)
          .fail
            width 106px
            height: 40px;
            line-height 16px
            background: #FFFFFF url('~assets/img/icon_fail@2x.png') no-repeat 10px center / 16px;
            box-shadow: 0px 0px 6px 2px rgba(0, 0, 0, 0.06);
            border-radius: 8px;
            padded_box(border-box, 12px 10px 12px 38px)
            font-size 14px
            color #222222
            position absolute
            top 50%
            left 50%
            transform translate(-50%, -50%)
        .descript
          line-height 20px
          font-size 12px
          color #7F7F7F
          &.icon-scancode
            background url('~assets/img/icon_scancode@2x.png') no-repeat 0 top / 20px
            padded_box(border-box, 0 0 0 24px)
          .descript-btn
            color #4c84ff
            cursor pointer

</style>
